using System;
using System.Linq;
using System.Linq.Expressions;
using Magiq.Behaviors;

namespace Magiq.Insert
{
    public class Insert<TSource, TDestination, TNew> : BehaviorHandler<IInsertBehavior>,
                                                       IInsert<TSource, TDestination, TNew>
        where TNew : class, TDestination, new() where TDestination : class
    {
        public Insert(IQueryable<TSource> source, Expression<Func<TSource, TNew>> newValueExpression,
                      IQueryable<TDestination> destination, IMagiqBehavior behavior)
            : base(behavior)
        {
            Default<DefaultInsertBehavior>();
            Destination = destination;
            Source = source;
            NewExpression = newValueExpression;
        }

        #region IInsert<TSource,TDestination,TNew> Members

        public Expression<Func<TSource, TNew>> NewExpression { get; private set; }

        public IQueryable<TSource> Source { get; private set; }

        public IQueryable<TDestination> Destination { get; private set; }

        IMagiqBehavior IBehaviorBasedExecution.Behavior
        {
            get { return BehaviorChain; }
        }

        #endregion

        public int Execute()
        {
            var strategy = Call(x => x.GetInsertStrategy(this));
            return Call(x => x.Execute(strategy));
        }
    }
}